package com.dingding.special.order.confirm.dao.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.dao.impl.BaseDaoImpl;
import com.dingding.common.core.base.daox.IBaseDaoX;
import com.dingding.common.core.base.daox.ICriteriaBaseDao;
import com.dingding.common.core.base.dto.ResponseEntity;
import com.dingding.common.core.beans.special.Userspecialorder;
import com.dingding.common.core.beans.special.UserspecialorderT;
import com.dingding.common.core.push.base.ClientAppType;
import com.dingding.facade.account.user.service.IUserAccountService;
import com.dingding.order.code.order.SpecialOrderStatus;
import com.dingding.order.common.dto.distance.ResRealTimeCalculationDTO;
import com.dingding.special.order.aboard.code.ConfirmAboardCodeMsg;
import com.dingding.special.order.confirm.dao.IConfirmArriveDao;
import com.dingding.special.order.confirm.dto.ConfirmArriveNoticeDTO;
import com.dingding.special.order.confirm.dto.ReqConfirmArriveDTO;
import com.dingding.special.order.confirm.dto.ResConfirmArriveDTO;
import com.dingding.special.order.confirm.sql.ConfirmArriveSQL;

/**
 * 
 * @ClassName: ConfirmArriveDaoImpl 
 * @Description:  确认到达DAO实现类
 * @author YHQ
 * @date 2016年8月21日 下午6:01:18
 * @since V2.4.0
 * 
 */
@SuppressWarnings("deprecation")
@Component("confirmArriveDao")
public class ConfirmArriveDaoImpl extends BaseDaoImpl<UserspecialorderT> implements IConfirmArriveDao{

	private Logger log = Logger.getLogger(this.getClass());
	
	@Resource(name = "baseDaoX")
	private IBaseDaoX basedao;
	
	@Resource(name = "criteriaBaseDao")
	private ICriteriaBaseDao criteriaBaseDao;
	
	@Resource(name = "userAccountService")
	private IUserAccountService userAccountService;
	
	/**
	 * 
	 * @Title: getSpecialOrdert 
	 * @Description: 根据用户Id获取专车未完成订单列表 
	 * @param userId 用户Id
	 * @author YHQ 
	 * @return List<Userspecialordert>    返回类型
	 * 
	 */
	@Override
	@Transactional(readOnly=true)
	public List<UserspecialorderT> getSpecialOrdert(String userId) {
		
		Criterion criterion = Restrictions.eq("grabOrderUserId", userId);
		
		try {
			return super.queryCriteriaList(criterion);
		} catch (Exception e) {
			log.error("根据用户Id获取专车未完成订单列表时出现异常   类："+this.getClass()+" getSpecialOrdert()", e);
		}
		
		return null;
	}

	/**
	 * 
	 * @Title: OrderTempToFormal 
	 * @Description: 专车的临时订单迁移到正式订单
	 * @param id 订单Id
	 * @author YHQ 
	 * 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void OrderTempToFormal(String id) {
		
		UserspecialorderT userspecialorderT = super.getById(id);
		Userspecialorder orderNew = new Userspecialorder();
		BeanUtils.copyProperties(userspecialorderT, orderNew);
		orderNew.setSpecialOrderId(userspecialorderT.getSpecialOrderId());
		orderNew.setOrderStatus(SpecialOrderStatus.ORDER_OK);
		orderNew.setIsComment(1);
		
		try {
			this.basedao.save(orderNew);
			this.basedao.delete(userspecialorderT);
		} catch (Exception e) {
			log.error("迁移订单出错！SpecialOrderDaoImpl：OrderTempToFormal()",e);
		}
	}
	
	/**
	 * 
	 * @Title: getSpecialOrdertInfo 
	 * @Description: 根据订单Id获取订单信息
	 * @param oid 订单Id
	 * @author YHQ 
	 * @since V2.4.0
	 * @return Userspecialordert    返回类型
	 * 
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public UserspecialorderT getSpecialOrdertInfo(String oid) {
		
		try {
			return super.getById(oid);
		} catch (Exception e) {
			log.error("根据订单Id获取订单信息时出现异常  类："+this.getClass()+" getSpecialOrdertInfo()", e);
		}
		
		return null;
	}
	
	/**
	 * 
	 * @Title: getNoticeInfo 
	 * @Description: 根据订单Id获取通知的信息 
	 * @param oid 订单Id
	 * @author YHQ 
	 * @since V2.4.0
	 * @return ConfirmAboardNoticeDTO    返回类型
	 * 
	 */
	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly=true)
	public ConfirmArriveNoticeDTO getNoticeInfo(String oid) {
		
		try {
			
			// 根据订单Id获取订单信息
			List<ConfirmArriveNoticeDTO> confirmArriveNoticeDTOs = (List<ConfirmArriveNoticeDTO>) super.listSqlFreeObject(ConfirmArriveSQL.GET_CONFIRM_ARRIVE_NOTICE_INFO, ConfirmArriveNoticeDTO.class, oid);
		
			// 判断获取的通知消息是否存在
			if(confirmArriveNoticeDTOs != null && confirmArriveNoticeDTOs.size() > 0){
				
				ConfirmArriveNoticeDTO dto = confirmArriveNoticeDTOs.get(0);
				
				if(dto.getLoginEquipment() == 1){
					dto.setClientType(ClientAppType.iOS.toString());
				}else{
					dto.setClientType(ClientAppType.Android.toString());
				}
				
				if(dto.getPublishType() == 3){
					dto.setOrderStatus(4);
				}else{
					dto.setOrderStatus(5);
				}
				
				return confirmArriveNoticeDTOs.get(0);
			}
			
		} catch (Exception e) {
			log.error("根据订单Id获取通知的信息 时出现异常  类："+this.getClass()+" getNoticeInfo()", e);
		}
		
		return null;
	}
	
	
	/**
	 * 
	 * @Title: confirmArriveOperation 
	 * @Description: 确认达到操作 
	 * @param response 确认到达响应Bean
	 * @param reqConfirmArriveDTO 确认到达客户端请求Bean
	 * @author YHQ 
	 * @since V2.4.0
	 * @return boolean    返回类型
	 * 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean confirmArriveOperation(ResponseEntity<ResConfirmArriveDTO> response,ReqConfirmArriveDTO reqConfirmArriveDTO,ResRealTimeCalculationDTO resCalculationAmount){
		

		// 根据订单Id获取订单信息
		UserspecialorderT userspecialordert = this.getSpecialOrdertInfo(reqConfirmArriveDTO.getOid());
		
		// 确认达到响应Bean
		ResConfirmArriveDTO resConfirmArriveDTO = new ResConfirmArriveDTO();
		
		// 订单不存在
		if(userspecialordert == null){
			
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(ConfirmAboardCodeMsg.ORDER_NOT_EXIST);// 订单不存在
			response.setPromptMessage(ConfirmAboardCodeMsg.ORDER_NOT_EXIST);// 订单不存在
			return false;
		}
		
		// 订单状态不是待上车
		if(userspecialordert.getOrderStatus() != 3){
			
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(ConfirmAboardCodeMsg.CONFIRM_ABOARD_ORDER_STATUS_ERROR);// 该订单不是已上车状态
			response.setPromptMessage(ConfirmAboardCodeMsg.CONFIRM_ABOARD_ORDER_STATUS_ERROR);// 该订单不是已上车状态
			return false;
		}
		
		// 如果订单为一口价，则做订单迁移
		if(userspecialordert.getPublishType().equals(4)){
			
			// 迁移订单
			this.OrderTempToFormal(reqConfirmArriveDTO.getOid());
			// 订单状态
			userspecialordert.setOrderStatus(5);
			
			// 给司机转账
			this.userAccountService.recharge(userspecialordert.getGrabOrderUserId(), userspecialordert.getTotalMoney());
			
		}else{
			// 订单状态
			userspecialordert.setOrderStatus(4);
		}
		
		// 确认达到经度
		userspecialordert.setDebusLongitude(reqConfirmArriveDTO.getDebusLongitude());
		// 确认达到纬度
		userspecialordert.setDebusLatitude(reqConfirmArriveDTO.getDebusLatitude());
		// 确认到达时间
		userspecialordert.setEndTime(new Date());
		// 订单实际金额
		userspecialordert.setTotalMoney(resCalculationAmount.getAmount());
		// 订单实际里程
		userspecialordert.setDistance(resCalculationAmount.getDistance());
		// 订单时长
		userspecialordert.setDuration(resCalculationAmount.getDuration());
		
		// 设置订单状态
		resConfirmArriveDTO.setOrderStatus(userspecialordert.getOrderStatus());
		// 叮叮费用
		resConfirmArriveDTO.setTotalMoney(userspecialordert.getTotalMoney());
		
		response.setCode(HttpStatus.SC_OK);
		response.setResponseBody(resConfirmArriveDTO);
		
		return true;
	}
	
}
